package com.nsqt.common.controller;

import org.apache.commons.io.FileUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Java2word {

    public Java2word() {

    }

    /**
     * @param args
     */

    public static void main(String[] args) {
        Java2word j2w = new Java2word();
        try {
            ArrayList<File> resultList = new ArrayList<>();
            ArrayList<File> fileList = j2w.getFiles("C:\\Users\\admin\\Downloads\\main\\", resultList);
            StringBuffer resultFile = new StringBuffer();
            for (File file : resultList
            ) {

                BufferedReader reader = null;
                StringBuffer sbf = new StringBuffer();
                try {
                    reader = new BufferedReader(new FileReader(file));
                    String tempStr;
                    while ((tempStr = reader.readLine()) != null) {
                        sbf.append(tempStr);
                        sbf.append("\n");
                    }
                    reader.close();
                    sbf.append("\n");
                    resultFile.append(sbf);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
                sbf.append("\n");
                // resultFile.append(sbf);
            }

            FileUtils.writeStringToFile(new File("C:\\Users\\admin\\Downloads\\test.txt"), resultFile.toString());

        } catch (Exception e) {

        }

    }

    public ArrayList<File> getFiles(String path, ArrayList<File> resultList) throws Exception {
//目标集合fileList
        ArrayList<File> fileList = new ArrayList<File>();
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileIndex : files) {
//如果这个文件是目录，则进行递归搜索
                if (fileIndex.isDirectory()) {
                    getFiles(fileIndex.getPath(), resultList);
                } else {
//如果文件是普通文件，则将文件句柄放入集合中
                    resultList.add(fileIndex);
                }
            }
        }
        return resultList;
    }

}
